/*
 * Classe DBXmlRequest
 * by CrociDB
 *
 */

#include "DBXmlRequest.h"

DBXmlRequest::DBXmlRequest(const char* host, const char* file)
{
    memset(ip, 0, sizeof(ip));
    memset(end_file, 0, sizeof(end_file));
    memset(request, 0, sizeof(request));
    porta = 80;

    tixml = new TiXmlDocument();

    h = NULL;

    struct hostent *h = NULL;

    WORD wVersao = MAKEWORD(2, 2);
    WSADATA wsData;
    WSAStartup(wVersao, &wsData);

    server = socket(AF_INET, SOCK_STREAM, 0);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(porta);

    strcpy(ip, host);

    if (isalpha(*ip))
    {
        h = gethostbyname(ip);
        addr.sin_addr.s_addr = *((unsigned long *)h -> h_addr);

    }
    else
    {
        addr.sin_addr.s_addr = inet_addr(ip);
    }

    strcpy(end_file, file);

    sprintf(request, "GET /%s HTTP/1.1\r\n%s%s", end_file,
        "Accept: */*\r\nAccept-Encoding: gzip, deflate\r\n",
        "Host: 200.100.115.168\r\nConnection: Keep-Alive\r\nCache-Control: no-cache\r\n\r\n");
}

void DBXmlRequest::setHost(const char* host)
{
    strcpy(ip, host);

    if (isalpha(*ip))
    {
        h = gethostbyname(ip);
        addr.sin_addr.s_addr = *((unsigned long *)h -> h_addr);

    }
    else
    {
        addr.sin_addr.s_addr = inet_addr(ip);
    }
}

void DBXmlRequest::setPorta(int p)
{
    addr.sin_port = htons(porta);
}

void DBXmlRequest::setFile(const char* file)
{
    strcpy(end_file, file);
}

bool DBXmlRequest::Download()
{
    char rec[10240];
    memset(rec, 0, sizeof(rec));

    if (connect(server, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
    {
        cout << "Error code #" << WSAGetLastError() << " nao pode conectar-se ao ip " << inet_ntoa(addr.sin_addr) << endl;
    }

    send(server, request, sizeof (request), 0);

    memset(rec, 0, sizeof(rec));
    if (recv(server, rec, sizeof(rec), 0) > 0)
    {
        string *a = new string(rec);
        //cout << a->c_str();

        int i = a->find("\r\n\r\n", 0);
        //cout << endl << i << endl;

        //cout << endl << endl;

        xml = a->substr(i+4, a->size());
        tixml->Parse(xml.c_str());

        //cout << xml.c_str();
        closesocket(server);
        return 1;
    }

    return 0;
}

const char *DBXmlRequest::getXmlString()
{
    return xml.c_str();
}

TiXmlDocument *DBXmlRequest::getTiXmlDocument()
{
    return tixml;
}

bool DBXmlRequest::SaveFile(const char *filename)
{
    FILE *file = fopen(filename, "w");

    for (int j = 0; j < xml.size(); j++)
    {
        fputc(xml.at(j), file);
    }

    fclose(file);
    return 1;
}

DBXmlRequest::~DBXmlRequest()
{
    //
}
